package wiki.zimo.certificate_manage.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 *
 * @author 子墨
 * @date 2018/10/18 22:01
 * @describe 导入导出Excel服务
 */
@Service
public class ExcelService {

    @Value("${file.upload-path}")
    private String uploadPath;

    /**
     * 导出数据Excel方法的封装
     * @author 子墨
     * @date 2018/10/15 9:15
     * @params [response, data, clazz, params, fileName]
     * @return void
     */
    public void doExportExcel(HttpServletResponse response, List data, Class clazz, ExportParams params, String fileName) throws IOException {

        if (data == null){
            return;
        }

        if (fileName == null ||  fileName.replaceAll(" ","").equals("")){
            fileName = "export";
        }

        Workbook workbook = ExcelExportUtil.exportExcel(params,clazz,data);
        response.setHeader("content-Type","application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8") + ".xls");
        response.setCharacterEncoding("UTF-8");

        if (workbook != null){
            workbook.write(response.getOutputStream());
            workbook.close();
        }

    }

    /**
     * 导入Excel方法的封装
     * @author 子墨
     * @date 2018/10/17 9:32
     * @params [fileName, clazz, params]
     * @return java.util.List
     */
    public List doImportExcel(String fileName, Class clazz, ImportParams params) throws Exception {
        File file = new File(uploadPath,fileName);
        InputStream inputStream = new FileInputStream(file);
        List list = ExcelImportUtil.importExcel(inputStream, clazz, params);
        if (file.exists()){
            file.delete();
        }
        return list;
    }

}
